package com.oocl.servlet.action;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.List;
import java.util.UUID;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.commons.io.IOUtils;
import org.apache.log4j.Logger;

import com.oocl.pojo.Dish;
import com.oocl.pojo.Merchant;
import com.oocl.service.DishManager;
import com.oocl.service.factory.DishManagerFactory;
import com.oocl.util.ValidateUtil;

@WebServlet("/sec/dishes/add.action")
public class AddDishActionServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	private static final Logger LOGGER = Logger.getLogger(AddDishActionServlet.class);
	
	private final int SIZE_THRESHOLD = 20 * 1024;
	private final int IMG_MAX_SIZE = 1024 * 1024;
	private final String S_ENCODING = "utf-8";
	private final String IMG_FOLDER_PATH = "images" + File.separator + "dishes";
	private final String IMG_STORE_LOCATION = System.getenv("CATALINA_HOME") + File.separator + "O2OFile" + File.separator + IMG_FOLDER_PATH;
	private final String TMP_DIR = System.getProperty("java.io.tmpdir");
	
	private DishManager dishManager = DishManagerFactory.getInstance();

	protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// prepare
		DiskFileItemFactory factory = new DiskFileItemFactory(SIZE_THRESHOLD, new File(TMP_DIR));
		ServletFileUpload upload = new ServletFileUpload(factory);
		upload.setHeaderEncoding(S_ENCODING);
		
		List<FileItem> items = null;
		try {
			items = upload.parseRequest(request);
		} catch (FileUploadException e) {
			LOGGER.debug("request cannot be parsed", e);
		}
		if (items == null) {
			request.setAttribute("dNameError", "request cannot be parsed");
			request.getRequestDispatcher("add").forward(request, response);
			return;
		}
		
		// receive parameter
		String _dName = null;
		String _dPrice = null;
		String _dType = null;
		FileItem _dImage = null;
		for (FileItem item : items) {
			if (item.isFormField()) {
				String itemValue = item.getString(S_ENCODING);
				switch (item.getFieldName()) {
				case "dname":
					_dName = itemValue;
					break;
				case "dprice":
					_dPrice = itemValue;
					break;
				case "dtype":
					_dType = itemValue;
					break;
				}
			} else {
				_dImage = item;
			}
		}
		
		// validate
		boolean isValid = true;
		if (ValidateUtil.isNullOrEmpty(_dName)) {
			request.setAttribute("dNameError", "名称未填写");
			isValid = false;
		}
		if (ValidateUtil.isNullOrEmpty(_dPrice) || !ValidateUtil.isDouble(_dPrice)) {
			request.setAttribute("dPriceError", "价格未填写或不合法");
			isValid = false;
		}
		if (ValidateUtil.isNullOrEmpty(_dType) || !ValidateUtil.isInteger(_dType)) {
			request.setAttribute("dTypeError", "类型无效");
			isValid = false;
		}
		if (_dImage.getSize() <= 0) {
			request.setAttribute("dImageError", "图片未上传");
			isValid = false;
		}
		if (_dImage.getSize() > IMG_MAX_SIZE) {
			request.setAttribute("dImageError", "图片过大");
			isValid = false;
		}
		if (!isValid) {
			request.setAttribute("form_dName", _dName);
			request.setAttribute("form_dPrice", _dPrice);
			request.setAttribute("form_dType", _dType);
			request.getRequestDispatcher("add").forward(request, response);
			return;
		}
		
		// generate uuid
		String dId = UUID.randomUUID().toString();
		
		// get image extension name
		String filename = _dImage.getName();
		String extName = filename.substring(filename.lastIndexOf('.'));
		String fileStorePath = IMG_STORE_LOCATION + File.separator + dId + extName;
		String pathInDB = IMG_FOLDER_PATH + File.separator + dId + extName;

		// upload file and get path
		InputStream in = _dImage.getInputStream();
		FileOutputStream fos = new FileOutputStream(fileStorePath);
		IOUtils.copy(in, fos);
		in.close();
		fos.close();
		
		// type convert
		Double dPrice = Double.parseDouble(_dPrice);
		Integer dType = Integer.parseInt(_dType);
		
		// wrap
		// TODO session
		Merchant m = (Merchant) request.getSession().getAttribute("merchant");
		Dish d = new Dish(dId, _dName, dPrice, pathInDB, dType, m.getmId());
		
		// call service
		dishManager.addDish(d);
		response.sendRedirect("list");
	}

}
